/**
 * weapp-js v1.7.1(2021-4-16)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2021 Motigo, Inc.
 * 
 */
/* 业务请求缓存
    - 通过set设置缓存数据，支持过期时间expire_in，单位秒
    - 通过get获取缓存数据
    - 存储在storage里：wx.setStorage、wx.getStorage
    - 为了加快判断数据是否过期，将cache的数据和过期时间分开两个key存放
 */

export default {
    enable: true,
    disable() {
        this.enable = false;
    },
    /* 设置缓存数据
        参数：
            - path: 请求地址，如/shops
            - params: 请求参数，可无
            - expire_in: 过期时间，单位秒
            - data: 缓存的数据
     */
    set(path, params, expire_in, data) {
        expire_in = expire_in || 24 * 3600 * 7; // 默认缓存7天
        let data_key = this._cacheDataKey(path, params);

        // 保存数据
        wx.setStorage({
            key: data_key,
            data: data
        });

        // 保存过期时间数据
        wx.setStorage({
            key: this._cacheExpireKey(path, params),
            data: Date.now() + expire_in * 1000
        });
    },
    /* 从缓存获取数据
        参数：
            - path: 请求地址，如/shops
            - params: 请求参数，可无
            - enable_cache放在这里，只是为了上层调用是，不要以为判断enable_cache而再promise，让写法简单一些
     */
    get(path, params, enable_cache) {
        return new Promise((resolve, reject) => {
            if (this.enable && enable_cache === true) {
                if (this._isCacheValid(path, params)) {
                    let cache_key = this._cacheDataKey(path, params);
                    wx.getStorage({
                        key: cache_key,
                        success: res=>{
                            // console.info('get from cache', cache_key);
                            resolve(res.data);
                        },
                        fail:()=>{
                            reject();
                            this._removeCache(path, params);
                        }
                    })
                } else {
                    this._removeCache(path, params);
                    reject();
                }
            } else {
                reject();
            }
        });
    },
    clearExpiredData() {
        wx.getStorageInfo({
            success(res) {
                res.keys.forEach(k => {
                    if (k.startsWith('[cache_expire]')) {
                        let t = wx.getStorageSync(k);
                        if (t < Date.now()) { // 过期
                            console.log('clear expire key:', k);
                            wx.removeStorage({
                                key: k
                            })

                            wx.removeStorage({
                                key: k.replace('[cache_expire]', '[cache]')
                            })
                        }
                    }
                });
            }
        })
    },
    // cache数据的key
    _cacheDataKey(path, params) {
        let url_param = this._jsonToUrlParams(params);
        let url = url_param ? `${path}?${url_param}` : path;

        return '[cache]' + url;
    },
    // cache expire的key
    _cacheExpireKey(path, params) {
        let url_param = this._jsonToUrlParams(params);
        let url = url_param ? `${path}?${url_param}` : path;

        return '[cache_expire]' + url;
    },
    _isCacheValid(path, params) {
        let data = wx.getStorageSync(this._cacheExpireKey(path, params));
        return (data && data > Date.now());
    },
    _removeCache(path, params) {
        wx.removeStorage({
            key: this._cacheDataKey(path, params)
        })

        wx.removeStorage({
            key: this._cacheExpireKey(path, params)
        })
    },
    _jsonToUrlParams(json_data) {
        let params = '';
        for (var k in json_data || {}) {
            params += '&' + k + '=' + encodeURIComponent(json_data[k]);
        }

        return params.length == 0 ? '' : params.slice(1, params.length);
    }
}